//
//  ComposeVC.swift
//  Swift微博
//
//  Created by adel on 2017/9/1.
//  Copyright © 2017年 com.bailun91. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposeVC: UIViewController {

    @IBOutlet weak var picPicerViewHCons: NSLayoutConstraint!
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    @IBOutlet weak var MytextView: ComposeTextView!
    @IBOutlet weak var picPickerView: PicPickerCollectionView!
    fileprivate lazy var titleView : ComposeTitleView  = ComposeTitleView()
    fileprivate lazy var images = [UIImage]()
    fileprivate lazy var emoticonVc : EmojViewController = EmojViewController {[weak self] (emoticon) -> () in
        
        self?.MytextView.insertEmoticon(emoticon: emoticon)
        self?.textViewDidChange(self!.MytextView)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavgationBar()
        setupNotifications()
       
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        MytextView.becomeFirstResponder()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    
}



// MARK:- 设置UI
extension ComposeVC{
    
    func setupNavgationBar() {
        
        // 1.设置左右的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(ComposeVC.closeItemClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(ComposeVC.sendItemClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        // 2.设置标题
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navigationItem.titleView = titleView
    }
    
    
    func  setupNotifications() {
        
         NotificationCenter.default.addObserver(self, selector:#selector(ComposeVC.keyboardWillChangeFrame(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
         NotificationCenter.default.addObserver(self, selector:#selector(ComposeVC.addPhotoClick), name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(ComposeVC.removePhotoClick(_:)), name: NSNotification.Name(rawValue: PicPickerRemovePhotoNote), object: nil)
    }
    
    // MARK:- 表情键盘
     @IBAction func emoticonBtnClick() {
        // 1.退出键盘
        MytextView.resignFirstResponder()
        
        // 2.切换键盘
        MytextView.inputView = MytextView.inputView != nil ? nil : emoticonVc.view
        
        // 3.弹出键盘
        MytextView.becomeFirstResponder()
        
    }
    
    // MARK:- 选择图片按钮
    @IBAction func picPickerBtnClick() {
        
        titleView.endEditing(true)
        
        // 执行动画
        picPicerViewHCons.constant = UIScreen.main.bounds.height * 0.65
        UIView.animate(withDuration: 0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }

        
    }
}


// MARK:- 按钮的点击事件
extension ComposeVC{
    
    @objc fileprivate func closeItemClick() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendItemClick() {
        view.endEditing(true)
        
        NETWorkTool.sharedNETWorkTool.sendStatus(MytextView.getEmoticonString()) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "发送微博失败")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发送微博成功")
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    

}

// MARK:- UITextView的代理方法
extension ComposeVC : UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
       MytextView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    
    
}




// MARK:- 通知事件监听
extension ComposeVC{
    
    // MARK:- 键盘监听
    func keyboardWillChangeFrame(_ note : NSNotification) {
        // 1.获取动画执行的时间
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        
        // 2.获取键盘最终Y值
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        
        // 3.计算工具栏距离底部的间距
        let margin = UIScreen.main.bounds.height - y
        
        // 4.执行动画
        toolBarBottomCons.constant = margin
        UIView.animate(withDuration: duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK:- 添加图片按钮监听
    func addPhotoClick(){
        
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        
        let ipc = UIImagePickerController()
        
        ipc.sourceType = .photoLibrary
        ipc.delegate = self
        present(ipc, animated: true, completion: nil)
    }
    
    // MARK:- 删除图片按钮
    func removePhotoClick(_ note : NSNotification) {
        
        guard let image = note.object as? UIImage else {
            return
        }
        
        // 2.获取image对象所在下标值
        guard let index = images.index(of: image) else {
            return
        }
        
        // 3.将图片从数组删除
        images.remove(at: index)
        
        // 4.重写赋值collectionView新的数组
        picPickerView.images = images
        
    }
}


extension ComposeVC : UINavigationControllerDelegate,UIImagePickerControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        images.append(image)
        picPickerView.images = images
        picker.dismiss(animated: true, completion: nil)

    }
}

